//个人中心

import UIKit

class MYGMyPageViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {
    let collectionArr = [["我的话题","我的微站","我的报道","收藏","点赞","我的云盘","我的简历"],
                         ["设置","帮助与反馈","清除缓存"]]
    let collectionImageNameArr = [["MYG_myPage_huati","MYG_myPage_weitie","MYG_myPage_baodao","MYG_myPage_shoucang","MYG_myPage_dianzan","MYG_myPage_yunpan","MYG_myPage_jianli"],["MYG_myPage_shezhi","MYG_myPage_fankui","MYG_myPage_huancun"]]
    let sectionHeaderArr = ["与我相关","设置"]
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "我的"
        self.view.backgroundColor = .white
        initUI()
        
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        getStatic()
        headerView.myHeaderImageV.sd_setImage(with:URL(string: MYGUserManager.getUser()?.doctor.avatar), placeholderImage: UIImage.init(named: "head"), context: nil)
        headerView.myNameLabel.text = MYGUserManager.getUser()?.doctor.name
        let hospital = MYGUserManager.getUser()?.doctor.hospital ?? ""
        let title = MYGUserManager.getUser()?.doctor.title ?? ""
        headerView.myInfoLabel.text = "\(hospital) \(title)"
    }
    
    func getStatic() {
        MYGNetwork<MYGMeAPI, MYGStatistics>.request(target: .microStatistics) {[weak self] item in
            self?.headerView.bindData(item)
        } failed: { _, error in
            
        }
    }
    func initUI(){
        view.addSubview(mainScrollView)
        mainScrollView.addSubview(mainContainerView)
        mainContainerView.addSubview(backImageV)
        mainContainerView.addSubview(headerView)
        mainContainerView.addSubview(mypageCollectionview)
        mainScrollView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        mainContainerView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
            make.width.equalTo(screenWidth)
        }
        backImageV.snp.makeConstraints { make in
            make.right.equalToSuperview()
            make.top.equalToSuperview().offset(statusBarHeight + 58)
            make.width.equalTo(210)
            make.height.equalTo(317)
        }
        headerView.snp.makeConstraints { make in
            make.left.top.right.equalToSuperview()
            make.height.equalTo(200)//280
        }
        mypageCollectionview.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(headerView.snp.bottom)
            make.height.equalTo(400)
        }
    }
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 2
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if section == 0{
            return 7
        }else{
            return 3
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        if kind == UICollectionView.elementKindSectionHeader {
            let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "Header", for: indexPath)
            let typeImageV = UIImageView()
            typeImageV.image = UIImage(named: "MYG_home_type")
            headerView.addSubview(typeImageV)
            typeImageV.snp.makeConstraints { make in
                make.left.equalToSuperview().offset(17.5)
                make.centerY.equalToSuperview()
                make.width.equalTo(3)
                make.height.equalTo(15)
            }
            let typeNameLabel = UILabel()
            typeNameLabel.textColor = RGBA(r: 51, g: 51, b: 51, a: 1)
            typeNameLabel.font = UIFont.systemFont(ofSize: 18, weight: .medium)
            typeNameLabel.text = sectionHeaderArr[indexPath.section]
            headerView.addSubview(typeNameLabel)
            typeNameLabel.snp.makeConstraints { make in
                make.left.equalTo(typeImageV.snp.right).offset(10.5)
                make.centerY.equalTo(typeImageV)
                make.height.equalTo(25)
            }
            return headerView
        }else{
            let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "footer", for: indexPath)
            // 配置头部视图
            headerView.backgroundColor = .lightGray
            
            return headerView
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        return CGSize(width: screenWidth, height: 60)
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if indexPath.section == 0{
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MYGMyPageCollectionViewCell", for: indexPath) as! MYGMyPageCollectionViewCell
            cell.titleLab.text = collectionArr[indexPath.section][indexPath.row]
            cell.titleImageV.image = UIImage(named: collectionImageNameArr[indexPath.section][indexPath.row])
            return cell
        }else{
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MYGSetCollectionViewCell", for: indexPath) as! MYGSetCollectionViewCell
            cell.titleLab.text = collectionArr[indexPath.section][indexPath.row]
            cell.titleImageV.image = UIImage(named: collectionImageNameArr[indexPath.section][indexPath.row])
            return cell
        }
        
    }
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if indexPath.section == 0 {
            if indexPath.row == 0 {
                let vc = MYGTopicViewController()
                self.navigationController?.pushViewController(vc, animated: true)
            }
            if indexPath.row == 1 {
                let vc = MYGMicrostationViewController()
                navigationController?.pushViewController(vc)
            }
            if indexPath.row == 2 {
                if ((MYGUserManager.getUser()?.doctor.name.isEmpty) == true) || MYGUserManager.getUser()?.doctor.gender == 0 || ((MYGUserManager.getUser()?.doctor.identity.isEmpty) == true) {
                    let vc = MYGBaseInfoController()
        //            vc.model = model
                    self.navigationController?.pushViewController(vc)
                    return
                }
                
                if MYGUserManager.isDoctorInfComplete  {
                    if MYGUserManager.getUser()?.doctor.status == 20 {
                        self.navigationController?.pushViewController(MYGMyReportsNewViewController(), animated: true)
                    }else {
                        MMYGHUD.showToast(text: "正在审核中，暂时无法使用该功能")
                    }
            
                }else {
                    let vc = MYGUpdateInfoViewController()
                    vc.model = MYGUserManager.getUser()!
                    vc.isEdit = true
                    self.navigationController?.pushViewController(vc)
                }
                
            }
            if indexPath.row == 3 {
                self.navigationController?.pushViewController(MYGMyCollectViewController(), animated: true)
            }
            if indexPath.row == 4 {
                self.navigationController?.pushViewController(MYGMyLikeViewController(), animated: true)
            }
            
            if indexPath.row == 5 {
                self.navigationController?.pushViewController(MYCloudDiskViewController(), animated: true)
            }
            if indexPath.row == 6 {
                let vc = MYGResumeViewController()
                navigationController?.pushViewController(vc)
            }
        }else
        if indexPath.section == 1 {
            if indexPath.row == 0 {
                self.navigationController?.pushViewController(MYGSettingController(), animated: true)
            }
            
            if indexPath.row == 1 {
                self.navigationController?.pushViewController(MYGFeedbackViewController(), animated: true)
            }
            if indexPath.row == 2 {
                self.clearCache()
            }
        }
        
    }
    lazy var mainScrollView: UIScrollView = {
        var view = UIScrollView()
        view.backgroundColor = .white
        view.showsVerticalScrollIndicator = false
        return view
    }()
    
    lazy var mainContainerView: UIView = {
        var view = UIView()
        view.backgroundColor = .white
        return view
    }()
    lazy var headerView:MYGMyPageHeaderView = {
        var view = MYGMyPageHeaderView()
        view.headerActionBlock = {[weak self] tag in
            let vc = MYGMyFollowsViewController()
            vc.pageType = tag - 99
            self?.navigationController?.pushViewController(vc, animated: true)
        }
        return view
    }()
    lazy var backImageV:UIImageView = {
        var view = UIImageView()
        view.image = UIImage(named: "MYG_myPage_mainBack")
        return view
    }()
    lazy var mypageCollectionview: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = 15
        layout.minimumInteritemSpacing = 0
        layout.itemSize = CGSize(width: screenWidth/4, height: 70)
        let collV = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
        collV.showsVerticalScrollIndicator = false
        collV.showsHorizontalScrollIndicator = false
        collV.register(MYGMyPageCollectionViewCell.self, forCellWithReuseIdentifier: "MYGMyPageCollectionViewCell")
        collV.register(MYGSetCollectionViewCell.self, forCellWithReuseIdentifier: "MYGSetCollectionViewCell")
        collV.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "Header")
        collV.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "footer")
        collV.isScrollEnabled = false
        collV.dataSource = self
        collV.delegate = self
        collV.backgroundColor = .clear
        return collV
    }()
}

extension MYGMyPageViewController {
    ///删除APP缓存
    func clearCache() {
        MMYGHUD.showToast(text: "清理成功")
        // 取出cache文件夹目录
        let cachePath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first
        let fileArr = FileManager.default.subpaths(atPath: cachePath!)
        // 遍历删除
        for file in fileArr! {
            let path = (cachePath! as NSString).appending("/\(file)")
            if FileManager.default.fileExists(atPath: path) {
                do {
                    try FileManager.default.removeItem(atPath: path)
                } catch {
                }
            }
        }
    }
}
